/**
 * 
 */
package arch.cpu.instruction;

import java.util.HashMap;
import java.util.Map;



/**
 * @author petery
 *
 */
public final class OperatorFactory
{
	private static Map<String, IOperator> operators = new HashMap<String, IOperator>();
	
	private OperatorFactory(){};
	
	public static IOperator createOperator(final String opcode)
	{
		if ( operators.containsKey(opcode) )
		{
			return operators.get(opcode);
		}
		
		IOperator newOperator = createByReflector(opcode);
		operators.put(opcode, newOperator);
		return newOperator;
	}
	
	private static IOperator createByReflector(final String opcode)
	{
		if ( null == opcode)
		{
			return null;
		}
		
		final StringBuffer operatorClassName = new StringBuffer(opcode);
		operatorClassName.replace(0, 1, operatorClassName.substring(0, 1).toUpperCase());
		operatorClassName.insert(0, "arch.cpu.instruction.");
		operatorClassName.insert(operatorClassName.length(), "Operator");

		
		try
		{
			return (IOperator) Class.forName(operatorClassName.toString()).newInstance();
		}
		catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
			
		}
		return null;
	}
}
